package 剑指offer_leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * JZ32从上往下打印二叉树
 */


public class 剑指Offer32_I_从上到下打印二叉树 {
    public int[] levelOrder(TreeNode root) {
        ArrayList<Integer> res =new ArrayList<>();
        if(root==null)
            return new int[0];
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        while(!q.isEmpty()){
            int size = q.size();
            while(size-->0){
                TreeNode n = q.poll();
                res.add(n.val);
                if(n.left!=null)
                    q.offer(n.left);
                if(n.right!=null)
                    q.offer(n.right);
            }
        }
        if(res.size()==0)
            return new int[0];
        int[] arr = new int[res.size()];
        for(int i=0;i<res.size();i++)
            arr[i] = res.get(i);
        return arr;
    }
}
